<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue'
import { Card, Form, FormItem, Row, Col, Input, Select, Divider, Button } from 'ant-design-vue'
import { useVbenModal } from '@vben/common-ui'
import print from 'vue3-print-nb'
// 引入打印样式（用于页面预览）
import '../styles/print-template.css'
// 引入打印样式内容（用于打印窗口）
import printStylesContent from '../styles/print-template.css?raw'

// 注册 vue3-print-nb 指令
const vPrint = print

/**
 * 定义组件接收的数据
 */
interface PrintData {
  templateType: string
  templateName: string
  goodsData: any
  sizeList: any[]
}

/**
 * 接收父组件传递的数据
 */
const printData = ref<PrintData | null>(null)

// 打印表单数据
const printForm = reactive({
  title_english: '',
  goods_no: '',
  template_name: '',
  template_no: '',
  color_name: '',
  size_id: '',
  size_name: '',
  grade: '',
  component: '',
  safe_type: '',
  exec_standard: '',
  inspector: '',
  sup_code: '',
  purchase_type_name: '',
  erp_brand: {} as any,
  supply_list: [] as any[],
  is_process: 0,
})

// 供应商编码
const suppCode = ref('')

// 尺码选项
const sizeOptions = computed(() => {
  if (!printData.value?.sizeList) return []
  return printData.value.sizeList.map((size: any) => ({
    label: size.name,
    value: size.id,
    name: size.name,
  }))
})

// 获取环境变量资源 URL
const resourceUrl = import.meta.env.VITE_GLOB_RESOURCES_URL || ''

/**
 * 品牌Logo图片
 */
const brandLogoUrl = computed(() => {
  if (printForm.erp_brand?.logo) {
    // 如果logo是完整URL，直接使用
    if (printForm.erp_brand.logo.startsWith('http')) {
      return printForm.erp_brand.logo
    }
    // 如果是相对路径，添加资源URL前缀
    return `${resourceUrl}${printForm.erp_brand.logo}`
  }
  // 默认图片
  return '/images/babiboy.jpg'
})

/**
 * 尺码选择变化
 */
const handleSizeChange = (sizeId: any) => {
  if (!printData.value?.sizeList) return
  const selectedSize = printData.value.sizeList.find((size: any) => size.id === sizeId)
  if (selectedSize) {
    printForm.size_id = sizeId
    printForm.size_name = selectedSize.name
  }
}

/**
 * 供应商编码选择变化
 */
const handleSupCodeChange = (val: any) => {
  suppCode.value = val
}

/**
 * 监听供应商编码变化，自动更新sup_code
 */
watch(() => suppCode.value, (newValue) => {
  // is_process 采购单标识 0-成品 1-加工订单
  if (printForm.is_process === 0) {
    printForm.sup_code = 'A' + newValue
  } else {
    printForm.sup_code = newValue
  }
})

/**
 * 初始化表单数据
 */
const initFormData = (data: PrintData) => {

  printData.value = data
  const goodsData = data.goodsData
  let name=data.templateType =='templateE'? goodsData.template_name +"\n \u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0(水洗产品)":goodsData.template_name  
  Object.assign(printForm, {
    title_english: goodsData?.title_english || '',
    goods_no: goodsData?.goods_no || '',
    template_name: name,
    template_no: goodsData?.template_no || '',
    color_name: goodsData?.color_name || '',
    size_id: goodsData?.size_id || '',
    size_name: goodsData?.size_name || '',
    grade: goodsData?.grade || '合格品',
    component: goodsData?.component || '',
    safe_type: goodsData?.safe_type || '',
    exec_standard: goodsData?.exec_standard || '',
    inspector: goodsData?.inspector || '08',
    sup_code: goodsData?.sup_code || '',
    purchase_type_name: goodsData?.purchase_type_name || '',
    erp_brand: goodsData?.erp_brand || {},
    supply_list: goodsData?.supply_list || [],
    is_process: goodsData?.is_process || 0,
  })
  
  // 如果有尺码列表但没有选中尺码，默认选中第一个
  if (data.sizeList.length > 0 && !printForm.size_id) {
    const firstSize = data.sizeList[0]
    printForm.size_id = firstSize.id
    printForm.size_name = firstSize.name
  }

  // 初始化供应商编码
  // if (printForm.supply_list.length > 0 && !suppCode.value) {
  //   suppCode.value = printForm.supply_list[0]?.SupplyCode || ''
  // }
}

/**
 * 打印配置
 * 注意：
 * 1. 打印样式已提取到独立的 CSS 文件中（print-template.css）
 * 2. 通过 Vite 的 ?raw 后缀直接导入 CSS 文件内容作为字符串
 * 3. 这样只需维护一份样式文件，预览和打印自动保持一致
 */
const printObj = {
  id: 'print-preview-content', // 打印区域的 id
  popTitle: '打印预览', // 打印窗口标题
  extraHead: `<style type="text/css">${printStylesContent}</style>`, // 直接使用导入的CSS内容
  preview: false, // 是否启用预览模式（默认直接打印）
  previewTitle: '打印预览', // 预览标题
  previewPrintBtnLabel: '打印', // 预览打印按钮文本
  zIndex: 20002, // 打印窗口的 z-index
}

/**
 * 使用 useVbenModal 管理弹窗
 */
const [Modal, modalApi] = useVbenModal({
  class: 'w-4/5',
  destroyOnClose:true,
  fullscreen: true,
  showConfirmButton: false, // 隐藏默认确认按钮，使用自定义打印按钮
  showCancelButton: true,
  cancelText: '关闭',
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      // 从父组件获取数据并初始化表单
      const data = modalApi.getData<PrintData>()
      if (data) {
        initFormData(data)
      }
    }
  },
})
</script>

<template>
  <Modal :title="`打印预览 - ${printData?.templateName || ''}`">
    <!-- 自定义底部按钮 -->
    <template #footer>
      <div class="flex justify-end gap-2">
        <Button @click="modalApi.close()">关闭</Button>
        <Button type="primary" v-print="printObj">
          打印标签
        </Button>
      </div>
    </template>

    <div class="print-preview-container">
      <Row :gutter="20" class="h-full">
        <!-- 左侧：表单编辑区 -->
        <Col :span="8" class="form-section">
          <Card title="信息编辑" :bordered="false" class="h-full">
            <Form :model="printForm" :label-col="{ style: { width: '110px' } }" :wrapper-col="{ style: { flex: 1 } }">
              <!-- 模板A、B、D、E 共有的字段 -->
              <template v-if="['templateA', 'templateB', 'templateD', 'templateE'].includes(printData?.templateType || '')">
                <FormItem label="品牌">
                  <Input v-model:value="printForm.title_english" />
                </FormItem>
                
                <FormItem label="货号">
                  <Input v-model:value="printForm.goods_no" />
                </FormItem>
                
                <FormItem label="品名">
                  <Input v-model:value="printForm.template_name" />
                </FormItem>
                
                <FormItem label="颜色">
                  <Input v-model:value="printForm.color_name" />
                </FormItem>
                
                <FormItem label="号型">
                  <Select 
                    v-model:value="printForm.size_id" 
                    :options="sizeOptions"
                    placeholder="请选择尺码"
                    @change="handleSizeChange"
                  />
                </FormItem>
                
                <FormItem label="等级">
                  <Input v-model:value="printForm.grade" />
                </FormItem>
                
                <FormItem label="成分" help="成品单：面料；加工单：加工面料">
                  <Input.TextArea 
                    v-model:value="printForm.component" 
                    :rows="1"
                    :auto-size="{ minRows: 1, maxRows: 5 }"
                  />
                </FormItem>
                
                <FormItem label="安全类别">
                  <Input.TextArea v-model:value="printForm.safe_type" :rows="1" />
                </FormItem>
                
                <FormItem label="执行标准">
                  <Input.TextArea v-model:value="printForm.exec_standard" :rows="1" />
                </FormItem>
                
                <FormItem label="简码">
                  <Input v-model:value="printForm.template_no" />
                </FormItem>

                <!-- 模板B和D有编码字段 -->
                <FormItem v-if="['templateB', 'templateD', 'templateE'].includes(printData?.templateType || '')" label="编码">
                  <Select
                    v-model:value="suppCode"
                    placeholder="请选择编码"
                    allow-clear
                    show-search
                    @change="handleSupCodeChange"
                  >
                    <Select.Option
                      v-for="item in printForm.supply_list"
                      :key="item.SupplyCode"
                      :label="item.sup_name"
                      :value="item.SupplyCode"
                    >
                      {{ item.sup_name }}
                    </Select.Option>
                  </Select>
                </FormItem>

                <FormItem label="采购单类型">
                  <Input v-model:value="printForm.purchase_type_name" disabled />
                </FormItem>
              </template>

              <!-- 模板C 特有的字段顺序 -->
              <template v-else-if="printData?.templateType === 'templateC'">
                <FormItem label="品名">
                  <Input v-model:value="printForm.template_name" />
                </FormItem>
                
                <FormItem label="安全类别">
                  <Input.TextArea v-model:value="printForm.safe_type" :rows="1" />
                </FormItem>
                
                <FormItem label="执行标准">
                  <Input.TextArea v-model:value="printForm.exec_standard" :rows="1" />
                </FormItem>
                
                <FormItem label="等级">
                  <Input v-model:value="printForm.grade" />
                </FormItem>
                
                <FormItem label="检验员">
                  <Input v-model:value="printForm.inspector" />
                </FormItem>
                
                <FormItem label="成分" help="成品单：面料；加工单：加工面料">
                  <Input.TextArea 
                    v-model:value="printForm.component" 
                    :rows="1"
                    :auto-size="{ minRows: 1, maxRows: 5 }"
                  />
                </FormItem>
                
                <FormItem label="颜色">
                  <Input v-model:value="printForm.color_name" />
                </FormItem>
                
                <FormItem label="简码">
                  <Input v-model:value="printForm.template_no" />
                </FormItem>
                
                <FormItem label="货号">
                  <Input v-model:value="printForm.goods_no" />
                </FormItem>

                <FormItem label="号型">
                  <Select 
                    v-model:value="printForm.size_id" 
                    :options="sizeOptions"
                    placeholder="请选择尺码"
                    @change="handleSizeChange"
                  />
                </FormItem>

                <FormItem label="采购单类型">
                  <Input v-model:value="printForm.purchase_type_name" disabled />
                </FormItem>
              </template>
            </Form>
          </Card>
        </Col>

        <!-- 右侧：打印预览区 -->
        <Col :span="16" class="preview-section">
          <Card title="打印效果预览" :bordered="false" class="h-full">
            <div id="print-preview-content">
              
              <!-- 模板 A -->
              <div v-if="printData?.templateType === 'templateA'" class="print-template template-a">
                <div class="care-template-box">
                  <div class="line-box">
                    <Divider class="top-divider" />
                  </div>
                  
                  <div class="brand">
                    <span class="brand-name">{{ printForm.title_english }}</span>
                    <span class="brand-logo">
                      <img :src="brandLogoUrl" alt="brand" class="brand-img" />
                    </span>
                  </div>
                  
                  <div class="content-box">
                    <div class="label-item">
                      <span>货号：</span>
                      <span class="label-value">{{ printForm.goods_no }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>品名：</span>
                      <span class="label-value" style="white-space: pre-wrap">{{ printForm.template_name }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>颜色：</span>
                      <span class="label-value">{{ printForm.color_name }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>号型：</span>
                      <span class="label-value">{{ printForm.size_name }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>等级：</span>
                      <span class="label-value">{{ printForm.grade }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>成分：</span>
                      <div class="component-text" v-html="printForm.component"></div>
                    </div>
                  </div>
                  
                  <div class="line-box">
                    <Divider class="bottom-divider" />
                  </div>
                  
                  <div class="other-info">
                    <div class="label-item">
                      <span class="title">安全类别：</span>
                      <span class="label-value content">{{ printForm.safe_type }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span class="title">执行标准：</span>
                      <span class="label-value content">{{ printForm.exec_standard }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>简码：</span>
                      <span class="label-value">{{ printForm.template_no }}</span>
                    </div>
                  </div>
                  
                  <div class="wash-box">
                    <div class="wash-title">洗涤方法：</div>
                    <div class="wash-list">
                      <img src="/images/print_temp/01/1.png" alt="" class="wash-img" />
                      <img src="/images/print_temp/01/2.png" alt="" class="wash-img" />
                      <img src="/images/print_temp/01/3.png" alt="" class="wash-img" />
                      <img src="/images/print_temp/01/4.png" alt="" class="wash-img" />
                      <img src="/images/print_temp/01/5.png" alt="" class="wash-img" />
                      <img src="/images/print_temp/01/6.png" alt="" class="wash-img" />
                    </div>
                  </div>
                  
                  <div class="remark-box">
                    <span>备注：请与相近颜色的制品同洗</span>
                  </div>
                </div>
                
                <div class="size-hint">
                  <span class="hint-text">总宽度：4CM × 总高度：13CM</span>
                </div>
              </div>

              <!-- 模板 B -->
              <div v-else-if="printData?.templateType === 'templateB' || printData?.templateType === 'templateE'" class="print-template template-b">
                <div class="care-template-box">
                  <div class="line-box">
                    <Divider class="top-divider" />
                  </div>
                  
                  <div class="brand">
                    <span class="brand-name">{{ printForm.title_english }}</span>
                    <span class="brand-logo">
                      <img :src="brandLogoUrl" alt="brand" class="brand-img" />
                    </span>
                  </div>
                  
                  <div class="content-box">
                    <div class="label-item">
                      <span>货号：</span>
                      <span class="label-value">{{ printForm.goods_no }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>品名：</span>
                      <span class="label-value" style="white-space: pre-wrap">{{ printForm.template_name }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>颜色：</span>
                      <span class="label-value">{{ printForm.color_name }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>号型：</span>
                      <span class="label-value">{{ printForm.size_name }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>等级：</span>
                      <span class="label-value">{{ printForm.grade }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>成分：</span>
                      <div class="component-text" v-html="printForm.component"></div>
                    </div>
                  </div>
                  
                  <div class="line-box">
                    <Divider class="bottom-divider" />
                  </div>
                  
                  <div class="other-info">
                    <div class="label-item">
                      <span class="title">安全类别：</span>
                      <span class="label-value content">{{ printForm.safe_type }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span class="title">执行标准：</span>
                      <span class="label-value content">{{ printForm.exec_standard }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>简码：</span>
                      <span class="label-value">{{ printForm.template_no }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>编码：</span>
                      <span class="label-value">{{ printForm.sup_code }}</span>
                    </div>
                  </div>
                  
                  <div class="wash-box">
                    <div class="wash-title">洗涤方法：</div>
                    <div class="wash-list">
                      <img src="/images/print_temp/01/1.png" alt="" class="wash-img" />
                      <img src="/images/print_temp/01/2.png" alt="" class="wash-img" />
                      <img src="/images/print_temp/01/3.png" alt="" class="wash-img" />
                      <img src="/images/print_temp/01/4.png" alt="" class="wash-img" />
                      <img src="/images/print_temp/01/5.png" alt="" class="wash-img" />
                      <img src="/images/print_temp/01/6.png" alt="" class="wash-img" />
                    </div>
                  </div>
                  
                  <div class="remark-box">
                    <span>备注：请与相近颜色的制品同洗</span>
                  </div>
                </div>
                
                <div class="size-hint">
                  <span class="hint-text">总宽度：4CM × 总高度：13CM</span>
                </div>
              </div>

              <!-- 模板 C：水洗唛外套 -->
              <div v-else-if="printData?.templateType === 'templateC'" class="print-template template-c">
                <div class="care-card-box">
                  <div class="top-table">
                    <div class="table-row bottom-border content-line">
                      <span class="data-title">品名：</span>
                      <span class="label-value" style="white-space: pre-wrap">{{ printForm.template_name }}</span>
                    </div>
                    
                    <div class="table-row bottom-border content-line">
                      <span class="data-title">安全技术类别：</span>
                      <span class="label-value">{{ printForm.safe_type || '' }}</span>
                    </div>
                    
                    <div class="table-row bottom-border content-line">
                      <span class="data-title">执行标准：</span>
                      <span class="label-value">{{ printForm.exec_standard || '' }}</span>
                    </div>
                    
                    <div class="table-row bottom-border">
                      <Row>
                        <Col :span="12" class="right-border">
                          <span class="data-title">等级：</span>
                          <span class="label-value">{{ printForm.grade }}</span>
                        </Col>
                        <Col :span="12">
                          <span class="data-title">检验员：</span>
                          <span class="label-value">{{ printForm.inspector }}</span>
                        </Col>
                      </Row>
                    </div>
                    
                    <div class="table-row bottom-border component-row">
                      <span class="data-title">成分：</span>
                      <div class="component-text" v-html="printForm.component"></div>
                    </div>
                    
                    <div class="table-row wash-row">
                      <span class="data-title">洗涤说明：</span>
                      <div class="wash-list">
                        <Row justify="center">
                          <Col :span="4" class="text-center">
                            <img src="/images/print_temp/01/7.png" alt="" class="wash-img" />
                          </Col>
                          <Col :span="4" class="text-center">
                            <img src="/images/print_temp/01/2.png" alt="" class="wash-img" />
                          </Col>
                          <Col :span="4" class="text-center">
                            <img src="/images/print_temp/01/3.png" alt="" class="wash-img" />
                          </Col>
                          <Col :span="4" class="text-center">
                            <img src="/images/print_temp/01/4.png" alt="" class="wash-img" />
                          </Col>
                          <Col :span="4" class="text-center">
                            <img src="/images/print_temp/01/5.png" alt="" class="wash-img" />
                          </Col>
                          <Col :span="4" class="text-center">
                            <img src="/images/print_temp/01/6.png" alt="" class="wash-img" />
                          </Col>
                        </Row>
                        <div class="wash-tip">建议使用中性洗涤剂洗涤</div>
                      </div>
                    </div>
                  </div>
                  
                  <div class="bottom-table">
                    <Row>
                      <Col :span="8" class="right-border brand-col">
                        <img src="/images/babiboy1.png" alt="brand" class="brand-img-full" />
                      </Col>
                      <Col :span="16">
                        <div class="bottom-border info-row">
                          <Row>
                            <Col :span="12" class="right-border info-col">
                              <span>颜色：</span>
                              <span class="break-word">{{ printForm.color_name }}</span>
                            </Col>
                            <Col :span="12" class="info-col">
                              <span class="break-word">{{ printForm.template_no }}</span>
                            </Col>
                          </Row>
                        </div>
                        <div class="info-row goods-row">
                          <span class="data-title">货号：</span>
                          <span class="break-word">{{ printForm.goods_no }}</span>
                        </div>
                      </Col>
                    </Row>
                  </div>
                </div>
                
                <div class="size-hint">
                  <h4 class="size-title">尺码说明</h4>
                  <p>1、总宽：40mm</p>
                  <p>2、总高：130mm；其中内容高度：100mm;上边距：15mm；底边距：15mm</p>
                </div>
              </div>

              <!-- 模板 D -->
              <div v-else-if="printData?.templateType === 'templateD'" class="print-template template-d">
                <div class="care-template-box">
                  <div class="line-box">
                    <Divider class="top-divider" />
                  </div>
                  
                  <div class="brand">
                    <span class="brand-name">{{ printForm.title_english }}</span>
                    <span class="brand-logo">
                      <img :src="brandLogoUrl" alt="brand" class="brand-img" />
                    </span>
                  </div>
                  
                  <div class="content-box">
                    <div class="label-item">
                      <span>货号：</span>
                      <span class="label-value">{{ printForm.goods_no }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>品名：</span>
                      <span class="label-value" style="white-space: pre-wrap">{{ printForm.template_name }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>颜色：</span>
                      <span class="label-value">{{ printForm.color_name }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>号型：</span>
                      <span class="label-value">{{ printForm.size_name }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>等级：</span>
                      <span class="label-value">{{ printForm.grade }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>成分：</span>
                      <div class="component-text" v-html="printForm.component"></div>
                    </div>
                  </div>
                  
                  <div class="line-box">
                    <Divider class="bottom-divider" />
                  </div>
                  
                  <div class="other-info">
                    <div class="label-item">
                      <span class="title">安全类别：</span>
                      <span class="label-value content">{{ printForm.safe_type }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span class="title">执行标准：</span>
                      <span class="label-value content">{{ printForm.exec_standard }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>简码：</span>
                      <span class="label-value">{{ printForm.template_no }}</span>
                    </div>
                    
                    <div class="label-item">
                      <span>编码：</span>
                      <span class="label-value">{{ printForm.sup_code }}</span>
                    </div>
                  </div>
                  
                  <div class="wash-box">
                    <div class="wash-title">洗涤方法：</div>
                    <div class="wash-list">
                      <img src="/images/print_temp/01/1.png" alt="" class="wash-img" />
                      <img src="/images/print_temp/01/2.png" alt="" class="wash-img" />
                      <img src="/images/print_temp/01/3.png" alt="" class="wash-img" />
                      <img src="/images/print_temp/01/4.png" alt="" class="wash-img" />
                      <img src="/images/print_temp/01/8.png" alt="" class="wash-img" />
                      <img src="/images/print_temp/01/6.png" alt="" class="wash-img" />
                    </div>
                  </div>
                  
                  <div class="remark-box">
                    <span>备注：请与相近颜色的制品同洗</span>
                  </div>
                </div>
                
                <div class="size-hint">
                  <span class="hint-text">总宽度：4CM × 总高度：13CM</span>
                </div>
              </div>

              <!-- 未选择模板时的提示 -->
              <div v-else class="text-center text-gray-500 mt-4">
                请选择打印模板
              </div>
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  </Modal>
</template>


<style scoped lang="scss">
/**
 * 打印预览容器样式
 * 打印内容样式已提取到 ../styles/print-template.css
 */
.print-preview-container {
  padding: 16px;

  .form-section,
  .preview-section {
    height: 100%;
  }

  :deep(.ant-card) {
    height: 100%;
    
    .ant-card-body {
      height: calc(100% - 57px);
      overflow-y: auto;
    }
  }

  :deep(.ant-form-item) {
    margin-bottom: 12px;
  }
}
</style>
